package com.shenma2009.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shenma2009.mapper.TbSecKillMapper;
import com.shenma2009.mapper.TbUserMapper;
import com.shenma2009.pojo.TbOrder;
import com.shenma2009.pojo.TbSecKill;
import com.shenma2009.pojo.TbUser;
import com.shenma2009.service.TbOrderService;
import com.shenma2009.mapper.TbOrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
* @author 33509
* @description 针对表【tb_order(订单表)】的数据库操作Service实现
* @createDate 2023-05-04 15:05:26
*/
@Service
@Slf4j
public class TbOrderServiceImpl extends ServiceImpl<TbOrderMapper, TbOrder>
    implements TbOrderService{

    @Autowired
    TbUserMapper tbUserMapper;

    @Autowired
    TbSecKillMapper tbSecKillMapper;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public boolean addSecKillOrder(Integer userId, Integer killId) {
        //-- 获取用户信息
        TbUser tbUser = tbUserMapper.selectById(userId);
        if(tbUser == null) {
            log.error("user:{}，用户不存在", userId);
            return false;
        }

        //-- 获取秒杀信息
        TbSecKill tbSecKill = tbSecKillMapper.selectById(killId);
        if(tbSecKill == null) {
            log.error("kill:{}，活动不存在", killId);
            return false;
        }

        //-- 生成订单
        TbOrder tbOrder = new TbOrder();
        tbOrder.setUserId(tbUser.getUserId());
        tbOrder.setUserName(tbUser.getUserName());

        tbOrder.setProducId(tbSecKill.getProducId());
        tbOrder.setProductName(tbSecKill.getProductName());
        tbOrder.setProductCount(1);

        tbOrder.setOrderAmount(tbSecKill.getKillMoney());

        save(tbOrder);

        //
        rabbitTemplate.convertAndSend("orderExchange", "", ""+tbOrder.getOrderId());

        return true;
    }
}




